import axios from 'axios';
import qs from 'qs';
import store from '../vuex/index';
import router from '../routers/index';
import login from './login/index';
import coupon from './coupon/index';
import cityCoupon from './cityCoupon/index';
import monthTicket from './month_ticket/index';
import platform_manage from './platform_manage/index';
import score from './score/index';
import park_vip from './park_vip/index';
import report from './report/index';
import park from './park/index';
import operation from './operation/index';

// axios 配置
axios.defaults.timeout = 60000 * 3;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.baseURL = '/mgr';

const isMicroNeedChangeUrl = function(url) {
	// 微服务名称--有添加新的微服务时在此数组内添加即可
	const MICRO_SERVICE_NAME = ['zbcloud/', 'park-config-service/', '/zbcloud/user-service/', '/static'];
	const microItem = MICRO_SERVICE_NAME.find(item => url.includes(item));
	return !!microItem;
};

const isPostJsonParamsRequest = url => {
	const postUrlList = [
		'mobile/parkingViolate/violateType/batchSave.do',
		'mobile/parkingLeaveReason/batchSave.do',
		'pomplog/updateMenuLogStatus.do',
		'operatorPark/',
		'valueAdded/batchDownloadQrCode',
		'channel/',
		'parkWebPhone/',
		'park/presentCar/clearByTopBillCodeList',
		'valueAdded/updateParkAlipayPidInfo',
		'valueAdded/getParkPayModeOpenPrcessInfo',
		'valueAdded/getOpenAlipayStatusVoList',
		'cenduty/seat/list',
		'cenduty/seat/add',
		'cenduty/seat/delete',
		'cenduty/seat/update',
		'user-service/sentryUser/getAll',
		'parkWebPhone/'
	];

	const notJSONUrlList = ['/zbcloud/user-service/sentryUser/forceOfDuty', 'operatorPark/uploadChannelLogo.do'];

	const isMicroUrl = isMicroNeedChangeUrl(url);
	const isNotJsonUrlList = !notJSONUrlList.find(item => url.includes(item));
	const isPostUrl = !!postUrlList.find(item => url.includes(item));
	return (isMicroUrl || isPostUrl) && isNotJsonUrlList;
};

//请求拦截
axios.interceptors.request.use(
	config => {
		config.headers['type'] = 'pomp';
		config.headers['user'] = localStorage.getItem('session_key');

		const _isMicro = isMicroNeedChangeUrl(config.url);
		if (_isMicro) {
			config.baseURL = '/';
			config.url = config.url.replace('mgr/', '');
		}

		const needLoading = url => {
			// 获取停车场树的时候不用显示loading框
			const DonotNeedLoading = [
				'isUniqueName.do',
				'verify_seccode.do',
				'parkingBaseData/getParkingBaseDataTree.do',
				'checkValidateCode',
				'hasExistParkName',
				'checkScaned',
				'config.do',
				'operatorPark/checkAreaNameExist',
				'main/openedOtherServiceList.do',
				'main/getParks.do',
				'park/findParkChannelTree.do',
				'park/findParkEnterChannelTree.do',
				'park/findParkAreaTree.do',
				'valueAdded/getQrCodeApplyForAlipay',
				'valueAdded/getOpenAlipayStatusVoList',
				'index/getUnreadMessageCount.do'
			];
			let isNeed = true;
			DonotNeedLoading.some(key => {
				if (url.indexOf(key) !== -1) {
					isNeed = false;
					return true;
				}
			});
			return isNeed;
		};

		if (needLoading(config.url)) {
			store.commit('LOADING_TOGGLE', true);
		}

		if (config.url.indexOf('api/v1/') > -1) {
			//读写卡特殊接口
			config.url = config.url.replace('/mgr', '');
			config.headers['authorization'] = 'Basic YWtlOmFrZTEyMw==';
			delete config.headers['user'];
			delete config.headers['type'];
			return config;
		} else if (!(config.data instanceof FormData)) {
			if (isPostJsonParamsRequest(config.url) && config.method === 'post') {
				config.headers.post['Content-Type'] = 'application/json';
			} else {
				config.data = qs.stringify(config.data);
			}
		}

		return config;
	},
	error => {
		store.dispatch('toastToggle', {
			info: '错误的传参',
			isToasting: true,
			time: 1200,
			icon: 2
		});
		return Promise.reject(error);
	}
);

//返回状态判断--拦截请求
// 0:会话过期 ,1：业务成功，2：业务失败，3，系统异常 4，未登录,5无权限操作
axios.interceptors.response.use(
	res => {
		let url = res.config.url;
		let _isMicro = isMicroNeedChangeUrl(url);

		if (url.indexOf('verify_seccode.do') == -1 && url.indexOf('parkingBaseData/getParkingBaseDataTree.do') == -1) {
			setTimeout(function() {
				store.commit('LOADING_TOGGLE', false);
			}, 300);
		}

		// 调用微服务的接口时执行
		if (_isMicro) {
			if (res.data && res.data.hasOwnProperty('status') && res.data.status == 500) {
				store.dispatch('toastToggle', {
					info: '服务器异常',
					isToasting: true,
					time: 1000,
					icon: 2
				});
				return Promise.reject(res);
			}
			if (res.data && res.data.hasOwnProperty('status') && res.data.status == 400) {
				store.dispatch('toastToggle', {
					info: res.data.message,
					isToasting: true,
					time: 1000,
					icon: 2
				});
				return Promise.reject(res);
			}
		} else {
			// 调用非微服务的接口时执行

			if (res.status != 200) {
				store.dispatch('toastToggle', {
					info: '网络或服务异常',
					isToasting: true,
					time: 1000,
					icon: 2
				});
				return Promise.reject(res);
			}
			let _status = res.data.status;
			let msg = '';
			switch (_status) {
				case 0:
					msg = '登录过期,请重新登录';
					break;
				case 2:
					msg = res.data.message;
					if (!msg || msg.length == 0) {
						msg = '网络或服务异常';
					}
					break;
				case 3:
					msg = res.data.message;
					if (!msg || msg.length == 0) {
						msg = '网络或服务异常';
					}
					break;
				case 4:
					msg = res.data.message;
					if (!msg || msg.length == 0) {
						msg = '未登录';
					}
					break;
				case 5:
					msg = res.data.message;
					if (!msg || msg.length == 0) {
						msg = '无权限操作';
					}
					break;
			}

			if (msg) {
				const DonotNeedToast = [
					'getAllImgInner.do',
					'menu.do',
					'checkValidateCode',
					'hasExistParkName',
					'checkScaned2'
				];
				const needToast = url => {
					let isNeed = true;
					DonotNeedToast.some(key => {
						if (url.indexOf(key) !== -1) {
							isNeed = false;
							return true;
						}
					});
					return isNeed;
				};
				if (needToast(url)) {
					store.dispatch('toastToggle', {
						info: msg,
						isToasting: true,
						time: 2000,
						icon: 2
					});
				}
			}

			if (_status !== undefined) {
				if (_status !== 1) {
					if (_status == 0 || _status == 4) {
						localStorage.setItem('isLogout', 0);
						router.push({
							name: 'login'
						});
					} else {
						return Promise.reject(res);
					}
				} else {
					return res;
				}
			}
		}

		return res;
	},
	error => {
		let message = new Error(error).toString();
		let url = error.config.url;
		if (message.indexOf('timeout') > -1) {
			store.commit('LOADING_TOGGLE', false);
			store.dispatch('toastToggle', {
				info: '请求超时',
				isToasting: true,
				time: 2000,
				icon: 2
			});
		} else {
			if (url.indexOf('api/v1/card/block') > -1) {
				//读卡器接口特殊处理
				store.dispatch('toastToggle', {
					info: '请在“下载中心”下载驱动安装后重试',
					isToasting: true,
					time: 1600,
					icon: 2
				});
			} else {
				store.dispatch('toastToggle', {
					info: '网络或服务异常',
					isToasting: true,
					time: 1200,
					icon: 2
				});
			}
		}
		setTimeout(function() {
			store.commit('LOADING_TOGGLE', false);
		}, 1200);

		return Promise.reject(error);
	}
);

export default {
	DelOrderExport(params) {
		return this.fetchGet('/authz/user/delOrderExport.do', params);
	},
	FindOrderExportList(params) {
		return this.fetchGet('/authz/user/findOrderExportList.do', params);
	},
	//获取菜单栏和权限
	GetMenu(params) {
		return this.fetchPost('/main/menu.do', params);
	},
	//获取菜单栏和权限
	GetNewMenu(params) {
		return this.fetchPost('/main/newmenu.do', params);
	},
	GetTableTreeData() {
		return this.fetchGet('/parkingBaseData/getParkingBaseDataTree.do');
	},
	login,
	coupon,
	cityCoupon,
	monthTicket,
	platform_manage,
	score,
	park_vip,
	report,
	park,
	operation,
	// GET请求
	fetchGet(url, params, otherParams) {
		return new Promise((resolve, reject) => {
			otherParams = otherParams || {};
			let _params = Object.assign({}, { params: params }, otherParams);
			axios
				.get(url, _params)
				.then(
					response => {
						resolve(response.data);
					},
					err => {
						reject(err);
					}
				)
				.catch(error => {
					reject(error);
				});
		});
	},
	// POST请求
	fetchPost(url, params, otherParams) {
		return new Promise((resolve, reject) => {
			otherParams = otherParams || {};
			axios
				.post(url, params, otherParams)
				.then(
					response => {
						resolve(response.data);
					},
					err => {
						reject(err);
					}
				)
				.catch(error => {
					reject(error);
				});
		});
	},
	// 用data接收参数
	fetchPostData(url, data) {
		return new Promise((resolve, reject) => {
			axios({
				method: 'post',
				url: url,
				data: data,
				responseType: 'blob'
			})
				.then(
					response => {
						resolve(response.data);
					},
					err => {
						reject(err);
					}
				)
				.catch(error => {
					reject(error);
				});
		});
	},
	fetchPostFile(url, formData) {
		let config = {
			headers: {
				'Content-Type': 'multipart/form-data'
			}
		};
		return new Promise((resolve, reject) => {
			axios
				.post(url, formData, config)
				.then(
					response => {
						resolve(response.data);
					},
					err => {
						reject(err);
					}
				)
				.catch(error => {
					reject(error);
				});
		});
	}
};
